const axios = require("axios");
const querystring = require('querystring');
const restul = require("./hand")

// 拼接token地址
// 小程序默认地址
let param = querystring.stringify({
    grant_type: "client_credential",
    appid: "wx1ad3074c99058f6a",
    secret: "58961fe3570c279abd1ae022804ddc87"
})

//获取token
let url = new URL(" https://api.weixin.qq.com/cgi-bin/token?") + param

// 云开发环境ID
let env = 'cloud1-0gtvjgkn812ec001'

//对云数据库操作的api Addurl添加 selurl查询 delurl删除
let Addurl = "https://api.weixin.qq.com/tcb/databaseadd?access_token="
let selurl = "https://api.weixin.qq.com/tcb/databasequery?access_token="
let delurl = "https://api.weixin.qq.com/tcb/databasedelete?access_token="
let updurl = "https://api.weixin.qq.com/tcb/databaseupdate?access_token="


class getToken {
    constructor() {

    }
    // 获取token
    async gettoken() {
        try {
            let token = await axios.get(url)
            if (token.status == 200) {
                return token.data.access_token
            } else {
                throw '获取token失败！'
            }
        } catch (e) {
            throw new restul(e, 500)
        }
    }
    // 调用云开发接口 对数据的增删改查(query)
    async postlive(dataurl, query) {
        try {
            let token = await this.gettoken()
            console.log("token",token)
            let data = await axios.post(dataurl + token, { env, query })
            if (data.data.errcode === 0) {
                return data.data
            } else {
                throw '请求出错'
            }
        } catch (e) {
            throw new restul(e, 500)
        }
    }


}

module.exports = {
    getToken,
    Addurl,
    selurl,
    delurl,
    updurl
}